﻿/*
Copyright (c) 2007-2011 William POTTIER - AllProgrammic

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using NetAccess.Common;
using NetAccess.Common.Exceptions;
using NetAccess.Formatters;
using NetAccess.Message;

namespace NetAccess.Server
{
    /// <summary>
    /// Server layer base class
    /// </summary>
    /// <typeparam name="T">BaseServerConnexion implementation</typeparam>
    public abstract partial class ServerLayer<T>
        where T : BaseServerConnexion
    {
        #region Fields
        /// <summary>
        /// Socket UDP pour la découverte des services
        /// </summary>
        private Socket _socketServiceDiscovery;
        /// <summary>
        /// Sémaphore pour l'auto découverte
        /// </summary>
        private ManualResetEvent _waitServiceDiscovery;
        /// <summary>
        /// Formatter de message pour la découverte automatique
        /// </summary>
        private MessageFormatter _serviceDiscoveryFormatter;
        #endregion

        private void StartServiceDiscovery()
        {
            try
            {
                // Création du socket UDP : utilisé pour la découverte automatique des serveurs
                _socketServiceDiscovery = new Socket(Configuration.ServiceDiscoveryIP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                
                if (Configuration.SendBufferSize > 0) _socketServiceDiscovery.SendBufferSize = Configuration.SendBufferSize;
                if (Configuration.ReceiveBufferSize > 0) _socketServiceDiscovery.ReceiveBufferSize = Configuration.ReceiveBufferSize;

                _socketServiceDiscovery.EnableBroadcast = true;
                _socketServiceDiscovery.Blocking = false;
                _socketServiceDiscovery.Bind(Configuration.ServiceDiscoveryEndPoint);

                _serviceDiscoveryFormatter = new MessageFormatter(_socketServiceDiscovery.ReceiveBufferSize);

                // Démarre le pool de découverte automatisé
                ThreadPool.QueueUserWorkItem(ListenServiceDiscovery);
            }
            catch (Exception ex)
            {
                State = ServerLayerState.Stopped;
                throw new NetAccessException(
                    "An error occured during starting TCPService. See InnerException for more informations", ex);
            }
        }

        private void StopServiceDiscovery()
        {
            if (_socketServiceDiscovery != null)
                _socketServiceDiscovery.Close();

            if (_waitServiceDiscovery != null)
                _waitServiceDiscovery.Close();

            _socketServiceDiscovery = null;
            _waitServiceDiscovery = null;
            _serviceDiscoveryFormatter = null;
        }

        private void ListenServiceDiscovery(object state)
        {
            _waitServiceDiscovery = new ManualResetEvent(false);

            while (State == ServerLayerState.Starting || State == ServerLayerState.Started)
            {
                try
                {
                    _waitServiceDiscovery.Reset();

                    var bufferServiceDiscovery = new byte[_socketServiceDiscovery.ReceiveBufferSize];
                    var ep = Configuration.ServiceDiscoveryEndPoint;
                    _socketServiceDiscovery.BeginReceiveFrom(
                        bufferServiceDiscovery,
                        0,
                        bufferServiceDiscovery.Length,
                        SocketFlags.None,
                        ref ep,
                        CallbackListenServiceDiscovery,
                        bufferServiceDiscovery);

                    _waitServiceDiscovery.WaitOne();
                }
                catch (ObjectDisposedException ex)
                {
                    Logger.Instance.Error(ex);
                    break;
                }
                catch (SocketException ex)
                {
                    Logger.Instance.Error(ex);
                }
            }
        }

        private void CallbackListenServiceDiscovery(IAsyncResult ar)
        {
            var remoteEndPoint = Configuration.ServiceDiscoveryEndPoint;
            var buffer = (byte[])ar.AsyncState;
            var numread = 0;

            try
            {
                numread = _socketServiceDiscovery.EndReceiveFrom(ar, ref remoteEndPoint);
            }
            catch (Exception ex)
            {
                if (State == ServerLayerState.Started) { Logger.Instance.Error(ex); }
            }

            try
            {
                // Restart listening
                _waitServiceDiscovery.Set();
            }
            catch (Exception ex)
            {
                if (State == ServerLayerState.Started) { Logger.Instance.Error(ex); }
            }

            if (numread > 0)
            {
                var ms = new MemoryStream(buffer, 0, numread);

                _serviceDiscoveryFormatter.AddDataToReception(ms.ToArray(), numread);
                var queue = _serviceDiscoveryFormatter.ProcessIncommingMessages();

                while (queue.Count > 0)
                {
                    var message = queue.Dequeue();
                    var appId = (String)message.MessageData[0];

                    if (message.MessageIdentifier != InternalMessageIdentifier.DiscoverServices ||
                        appId != Configuration.ApplicationIdentifier) continue;

                    var reponse = new InternalMessage(
                        InternalMessageIdentifier.DiscoverServices,
                        Configuration.ServerName,
                        Configuration.TCPServicePort,
                        0,
                        Configuration.IsEnableCompression,
                        Configuration.IsEnableEncryption,
                        Configuration.PublicKeyString,
                        _connexions.Count,
                        Configuration.MaxConnexions);

                    var fileSend = _serviceDiscoveryFormatter.Prepare(reponse);
                    while (fileSend.Count > 0)
                    {
                        _socketServiceDiscovery.SendTo(fileSend.Dequeue(), remoteEndPoint);
                    }
                }
            }
            else
            {
                // Le socket à été coupé
                Logger.Instance.Debug("Socket was unexpectedly ended.");
            }
        }
    }
}
